<?php
/**
 * 场次查看页面
 * 相对路径: adm/show.php
 * 作者: 15058593138@qq.com
 */

// 获取座位状态
if (isset($_GET['act']) && $_GET['act'] === 'getstatus') {
    $room = isset($_POST['room']) ? safeStr($_POST['room']) : '';
    $date = isset($_POST['date']) ? safeStr($_POST['date']) : '';
    $jieci = isset($_POST['jieci']) ? safeStr($_POST['jieci']) : '';
    
    if (empty($room) || empty($date) || empty($jieci)) {
        jsonMsg(0, '参数错误');
    }
    
    $db = new DB();
    $db->autoCreateDateTable($date);
    $recTable = TB_PREFIX . 'recs_' . $date;
    
    // 获取已预定座位
    $sql = "SELECT `iwei`, `usid`, `stats` FROM `{$recTable}` WHERE `room` = '{$room}' AND `days` = '{$jieci}' AND `stats` IN (1, 2)";
    $booked = $db->getAll($sql);
    
    $bookedSeats = [];
    foreach ($booked as $b) {
        $bookedSeats[$b['iwei']] = [
            'usid' => $b['usid'],
            'stats' => $b['stats']
        ];
    }
    
    $db->close();
    jsonMsg(1, '获取成功', $bookedSeats);
}

// 清退功能
if (isset($_GET['act']) && $_GET['act'] === 'clear') {
    $room = isset($_POST['room']) ? safeStr($_POST['room']) : '';
    $date = isset($_POST['date']) ? safeStr($_POST['date']) : '';
    $jieci = isset($_POST['jieci']) ? safeStr($_POST['jieci']) : '';
    
    if (empty($room) || empty($date) || empty($jieci)) {
        jsonMsg(0, '参数错误');
    }
    
    $db = new DB();
    $recTable = TB_PREFIX . 'recs_' . $date;
    
    // 标记为征用
    $sql = "UPDATE `{$recTable}` SET `stats` = 2 WHERE `room` = '{$room}' AND `days` = '{$jieci}' AND `stats` = 1";
    $result = $db->query($sql);
    
    // 记录到不可约JSON
    $buyue = readJson('./inc/buyue.json.php');
    $buyue[] = [
        'room' => $room,
        'date' => $date,
        'jieci' => $jieci
    ];
    writeJson('./inc/buyue.json.php', $buyue);
    
    $db->close();
    
    if ($result) {
        jsonMsg(1, '清退成功');
    } else {
        jsonMsg(0, '清退失败');
    }
}

// 管理员锁定座位
if (isset($_GET['act']) && $_GET['act'] === 'lock') {
    $room = isset($_POST['room']) ? safeStr($_POST['room']) : '';
    $date = isset($_POST['date']) ? safeStr($_POST['date']) : '';
    $jieci = isset($_POST['jieci']) ? safeStr($_POST['jieci']) : '';
    $seat = isset($_POST['seat']) ? safeStr($_POST['seat']) : '';
    
    if (empty($room) || empty($date) || empty($jieci) || empty($seat)) {
        jsonMsg(0, '参数错误');
    }
    
    $db = new DB();
    $db->autoCreateDateTable($date);
    $recTable = TB_PREFIX . 'recs_' . $date;
    
    // 检查座位是否已被预定
    $sql = "SELECT * FROM `{$recTable}` WHERE `room` = '{$room}' AND `days` = '{$jieci}' AND `iwei` = '{$seat}' AND `stats` IN (1, 2)";
    if ($db->getRow($sql)) {
        jsonMsg(0, '该座位已被预定或锁定');
    }
    
    // 锁定座位
    $unid = makeUnid();
    $hema = makeHema($date);
    
    $data = [
        'unid' => $unid,
        'usid' => 'admin_lock',
        'room' => $room,
        'ijie' => $date,
        'days' => $jieci,
        'iwei' => $seat,
        'hema' => $hema,
        'stats' => 2
    ];
    
    if ($db->insert($recTable, $data)) {
        $db->close();
        jsonMsg(1, '锁定成功');
    } else {
        $db->close();
        jsonMsg(0, '锁定失败');
    }
}

require_once './inc/head.php';

$rooms = readJson('./inc/weici.json.php');
$jiecis = readJson('./inc/jieci.json.php');
?>

<div class="container">
    <div style="background:#fff; padding:15px; border-radius:5px; margin-bottom:10px;">
        <h3>场次查看</h3>
        
        <div style="display:flex; gap:10px; margin-top:15px; flex-wrap:wrap;">
            <div class="form-group" style="flex:1; min-width:150px;">
                <label>选择教室</label>
                <select id="selectRoom" class="form-control">
                    <option value="">请选择教室</option>
                    <?php foreach ($rooms as $room): ?>
                        <option value="<?php echo $room['room']; ?>">
                            <?php echo $room['room']; ?> - <?php echo $room['name']; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group" style="flex:1; min-width:150px;">
                <label>选择日期</label>
                <input type="date" id="selectDate" class="form-control" 
                       value="<?php echo date('Y-m-d'); ?>"
                       min="<?php echo date('Y-m-d'); ?>"
                       max="<?php echo date('Y-m-d', strtotime('+30 days')); ?>">
            </div>
            
            <div class="form-group" style="flex:1; min-width:150px;">
                <label>选择节次</label>
                <select id="selectJieci" class="form-control">
                    <?php foreach ($jiecis as $j): ?>
                        <option value="<?php echo $j['code']; ?>">
                            <?php echo $j['name']; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-group" style="display:flex; align-items:flex-end; gap:5px;">
                <button class="btn btn-primary" onclick="loadSeats()">查看</button>
                <button class="btn btn-success" onclick="window.print()">打印</button>
                <button class="btn btn-danger" onclick="clearSession()">清退</button>
            </div>
        </div>
    </div>
    
    <div id="seatContainer" style="background:#fff; padding:20px; border-radius:5px; display:none;">
        <div style="text-align:center; margin-bottom:15px;">
            <h4 id="sessionInfo"></h4>
            <p style="color:#666; font-size:12px;">访问时间: <?php echo date('Y-m-d H:i:s'); ?></p>
        </div>
        
        <div style="text-align:center; margin-bottom:10px; color:#666;">
            前方 ← 讲台黑板 →
        </div>
        <div id="seatGrid" class="seat-grid"></div>
        <div style="text-align:center; margin-top:10px; color:#666; font-size:12px;">
            左前方：门 | 右后方：门
        </div>
        
        <div style="margin-top:15px; font-size:12px;">
            <span style="margin-right:15px;">
                <span style="display:inline-block; width:20px; height:20px; background:#fff; border:2px solid #ddd; vertical-align:middle;"></span>
                空闲
            </span>
            <span style="margin-right:15px;">
                <span style="display:inline-block; width:20px; height:20px; background:#28a745; vertical-align:middle;"></span>
                已约
            </span>
            <span>
                <span style="display:inline-block; width:20px; height:20px; background:#dc3545; vertical-align:middle;"></span>
                征用/锁定
            </span>
        </div>
    </div>
</div>

<script>
    let currentRoom = '';
    let currentLayout = '';
    
    // 教室座位配置
    const roomLayouts = <?php echo json_encode(array_column($rooms, 'layout', 'room')); ?>;
    const roomNames = <?php echo json_encode(array_column($rooms, 'name', 'room')); ?>;
    
    // 加载座位
    function loadSeats() {
        const room = document.getElementById('selectRoom').value;
        const date = document.getElementById('selectDate').value.replace(/-/g, '');
        const jieci = document.getElementById('selectJieci').value;
        
        if (!room) {
            toast('请选择教室', 'error');
            return;
        }
        
        currentRoom = room;
        currentLayout = roomLayouts[room];
        
        const jieciText = document.getElementById('selectJieci').selectedOptions[0].text;
        document.getElementById('sessionInfo').textContent = 
            `${roomNames[room]} - ${document.getElementById('selectDate').value} - ${jieciText}`;
        
        generateSeats();
        
        ajax('admin.php?do=show&act=getstatus', {room: room, date: date, jieci: jieci}, function(res) {
            if (res.code === 1) {
                updateSeatStatus(res.data);
                document.getElementById('seatContainer').style.display = 'block';
            } else {
                toast(res.msg, 'error');
            }
        });
    }
    
    // 生成座位
    function generateSeats() {
        const rows = currentLayout.split('|');
        const grid = document.getElementById('seatGrid');
        let html = '';
        let seatNum = 1;
        
        rows.forEach(rowSeats => {
            html += '<div class="seat-row">';
            for (let i = 0; i < parseInt(rowSeats); i++) {
                html += `<div class="seat" data-seat="${seatNum}">${seatNum}</div>`;
                seatNum++;
            }
            html += '</div>';
        });
        
        grid.innerHTML = html;
    }
    
    // 更新座位状态
    function updateSeatStatus(bookedSeats) {
        const seats = document.querySelectorAll('.seat');
        seats.forEach(seat => {
            const seatNum = seat.getAttribute('data-seat');
            seat.className = 'seat';
            seat.onclick = function() { lockSeat(seatNum); };
            
            if (bookedSeats[seatNum]) {
                const info = bookedSeats[seatNum];
                if (info.stats == 2) {
                    seat.className = 'seat occupied';
                    seat.style.background = '#dc3545';
                } else {
                    seat.className = 'seat occupied';
                    seat.style.background = '#28a745';
                }
                seat.title = '学号: ' + info.usid;
                seat.onclick = null;
            }
        });
    }
    
    // 锁定座位
    function lockSeat(seatNum) {
        const date = document.getElementById('selectDate').value.replace(/-/g, '');
        const jieci = document.getElementById('selectJieci').value;
        
        showModal('锁定座位', `<p>确定要锁定 ${seatNum} 号座位吗？</p>`, [
            {text: '取消', class: 'btn-secondary', onclick: 'closeModal()'},
            {text: '确定锁定', class: 'btn-primary', onclick: `doLock('${seatNum}', '${date}', '${jieci}')`}
        ]);
    }
    
    function doLock(seat, date, jieci) {
        const room = currentRoom;
        closeModal();
        
        ajax('admin.php?do=show&act=lock', {room: room, date: date, jieci: jieci, seat: seat}, function(res) {
            if (res.code === 1) {
                toast(res.msg, 'success');
                loadSeats();
            } else {
                toast(res.msg, 'error');
            }
        });
    }
    
    // 清退
    function clearSession() {
        const room = document.getElementById('selectRoom').value;
        const date = document.getElementById('selectDate').value.replace(/-/g, '');
        const jieci = document.getElementById('selectJieci').value;
        
        if (!room) {
            toast('请先查看场次', 'error');
            return;
        }
        
        showModal('清退确认', 
            `<p style="color:#dc3545;">此操作将清退该场次所有预定，并标记为征用状态！</p>
             <p>确定要继续吗？</p>`, [
            {text: '取消', class: 'btn-secondary', onclick: 'closeModal()'},
            {text: '确定清退', class: 'btn-danger', onclick: `doClear('${room}', '${date}', '${jieci}')`}
        ]);
    }
    
    function doClear(room, date, jieci) {
        closeModal();
        showLoading();
        
        ajax('admin.php?do=show&act=clear', {room: room, date: date, jieci: jieci}, function(res) {
            hideLoading();
            if (res.code === 1) {
                toast(res.msg, 'success');
                loadSeats();
            } else {
                toast(res.msg, 'error');
            }
        });
    }
</script>

<?php require_once './inc/foot.php'; ?>